#coding: utf8

import sys 
import os
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)



from gevent import server,pool,spawn,monkey
monkey.patch_all()

import time
import pymongo
import logging
import logging.config
import json
import socket

from topapi import *

from items_all import get_items_and_store_to_db
from trades_all import get_trades_and_store_to_db
from traderate_all import all_traderate_to_db


logging.config.fileConfig('./conf/log.conf')
slog = logging.getLogger('root')
mongo = pymongo.Connection('127.0.0.1:57324')

def process_a_new_user(db, user, retry=2):
    try_times = retry
    while try_times:
        try:
            get_items_and_store_to_db(Items(), db, user)
        except Exception as e:
            slog.warning('get_items_and_store_to_db fail[retry:%d]: %s' %(try_times, repr(e)))
            try_times -= 1
            continue
        break
    if not try_times:
        slog.fatal('get items and store to db fail')
    
    try_times = retry
    while try_times:
        try:
            get_trades_and_store_to_db(db, user)
        except Exception as e:
            slog.warning('get_trades_and_store_to_db fail[retry:%d]: %s' %(try_times, repr(e)))
            try_times -= 1
            continue
        break
    if not try_times:
        slog.fatal('get_trades_and_store_to_db fail')

    try_times = retry
    while try_times:
        try:
            all_traderate_to_db(db, user)
        except Exception as e:
            slog.warning('all_traderate_to_db fail[retry:%d]: %s' %(try_times, repr(e)))
            try_times -= 1
            continue
        break
    if not try_times:
        slog.fatal('all_traderate_to_db fail')

    try:
        incobj = Increment() 
        res = incobj.customer_permit(user['top_session'])
        slog.info('add permit increment for user success[session: %s][%s]' %(user['top_session'], repr(res)))
    except Exception as e:
        slog.warning('add permit increment for user fail[session: %s]: %s' %(user['top_session'], repr(e)))


def test_process_a_new_user():
    db = mongo.test 
    user = {
            'top_session': '6100830108c6629bc87406b2456bbc8d782cfc175620c68420839839',
    }
    process_a_new_user(db, user)


def spawn_new_user(user):
    slog.info('process new user: %s' %(repr(user)))
    process_a_new_user(mongo.taogold, user)
#shop rec
    for i in range(2):
        try:
            data = json.dumps(user)
            rec = socket.socket()
            rec.connect(('127.0.0.1', 8400))
            rec.send(data+'\n\n')
            if 'success' not in rec.recv(1024):
                raise Exception('fail: recommender not reutrn success')
            break
        except Exception as e:
            slog.warning('shop recommander for user[%s] fail: %s' %(repr(user), repr(e)))
#item correlation recommender
    for i in range(2):
        try:
            data = json.dumps(user)
            rec = socket.socket()
            rec.connect(('127.0.0.1', 8500))
            rec.send(data+'\n\n')
            if 'success' not in rec.recv(1024):
                raise Exception('fail: recommender not reutrn success')
            break
        except Exception as e:
            slog.warning('correlation recommander for user[%s] fail: %s' %(repr(user), repr(e)))



def test_gevent(js):
    print js


def srv_handle(socket, address):
    ct = socket.recv(1024)
    while not ct.endswith('\n\n'):
        ct += socket.recv(1024)
    try:
        u = json.loads(ct)
    except Exception as e:
        slog.warning('dump[%s] to json fail: %s' %(repr(ct), repr(e)))
        socket.send('fail\n\n')
        socket.close()
        return
    if 'top_session' not in u or 'nick' not in u:
        slog.warning('wrong data: %s' %(repr(ct)))
        socket.send('fail\n\n')
    else:
        spawn(spawn_new_user, u)
        socket.send('success\n\n')
    socket.close()

def srv():
    srv = server.StreamServer(('127.0.0.1', 8300), srv_handle)
    srv.serve_forever()


def main():
    try:
        pid = os.fork() 
        if pid>0:
            sys.exit(0)
    except Exception as e:
        sys.exit('fork #1 error: %s' %(str(e)))
    try:
        pid = os.fork() 
        if pid>0: 
            sys.exit(0)
    except Exception as e:
        sys.exit('fork #2 error: %s' %(str(e)))
    srv()

if __name__ == '__main__':
    #test_process_a_new_user()
    main()
    #srv()
